﻿using App.Core.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace App.Core.Helpers
{
    public static class UCPAASHelper
    {
        enum EBodyType : uint
        {
            EType_XML = 0,
            EType_JSON
        };

        const string m_mainAccount = "8aade5c270bbae702b5074bf5ec9b472";  //sid
        const string m_mainToken = "2af997c7fe5f216d4f3d61108f0b7d11";
        const string m_appId = "a25a94a03dd9495c858573d75f5af64b";  //对应的应用id，非测试应用需上线使用
        const string m_restAddress = "api.ucpaas.com";
        const string m_restPort = "443";
        const string softVer = "2014-06-30";
        const EBodyType m_bodyType = EBodyType.EType_JSON;

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="to">短信接收端手机号码</param>
        /// <param name="templateId">短信模板ID</param>
        /// <param name="param">内容数据，用于替换模板中{数字}</param>
        /// <exception cref="ArgumentNullException">参数不能为空</exception>
        /// <exception cref="Exception"></exception>
        /// <returns>包体内容</returns>
        public static string SendSMS(string to, string templateId, string param)
        {

            if (to == null)
            {
                throw new ArgumentNullException("to");
            }

            if (templateId == null)
            {
                throw new ArgumentNullException("templateId");
            }

            try
            {
                string date = DateTime.Now.ToString("yyyyMMddHHmmss");

                // 构建URL内容
                string sigstr = Utils.MD5Encrypt(m_mainAccount + m_mainToken + date);
                string uriStr;
                string xml = (m_bodyType == EBodyType.EType_XML ? ".xml" : "");
                uriStr = string.Format("https://{0}:{1}/{2}/Accounts/{3}/Messages/templateSMS{4}?sig={5}", m_restAddress, m_restPort, softVer, m_mainAccount, xml, sigstr);

                Uri address = new Uri(uriStr);

                // 创建网络请求  
                HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
                setCertificateValidationCallBack();

                // 构建Head
                request.Method = "POST";

                Encoding myEncoding = Encoding.GetEncoding("utf-8");
                byte[] myByte = myEncoding.GetBytes(m_mainAccount + ":" + date);
                string authStr = Convert.ToBase64String(myByte);
                request.Headers.Add("Authorization", authStr);


                // 构建Body
                StringBuilder data = new StringBuilder();

                if (m_bodyType == EBodyType.EType_XML)
                {
                    request.Accept = "application/xml";
                    request.ContentType = "application/xml;charset=utf-8";

                    data.Append("<?xml version='1.0' encoding='utf-8'?><templateSMS>");
                    data.Append("<appId>").Append(m_appId).Append("</appId>");
                    data.Append("<templateId>").Append(templateId).Append("</templateId>");
                    data.Append("<to>").Append(to).Append("</to>");
                    data.Append("<param>").Append(param).Append("</param>");
                    data.Append("</templateSMS>");
                }
                else
                {
                    request.Accept = "application/json";
                    request.ContentType = "application/json;charset=utf-8";

                    data.Append("{");
                    data.Append("\"templateSMS\":{");
                    data.Append("\"appId\":\"").Append(m_appId).Append("\"");
                    data.Append(",\"templateId\":\"").Append(templateId).Append("\"");
                    data.Append(",\"to\":\"").Append(to).Append("\"");
                    data.Append(",\"param\":\"").Append(param).Append("\"");
                    data.Append("}}");
                }

                byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());

                // 开始请求
                using (Stream postStream = request.GetRequestStream())
                {
                    postStream.Write(byteData, 0, byteData.Length);
                }

                // 获取请求
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    // Get the response stream  
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    string responseStr = reader.ReadToEnd();

                    if (responseStr != null && responseStr.Length > 0)
                    {
                        return responseStr;
                    }
                }
                return null;
            }
            catch (Exception e)
            {

                throw e;
            }

        }

        /// <summary>
        /// 设置服务器证书验证回调
        /// </summary>
        public static void setCertificateValidationCallBack()
        {
            System.Net.ServicePointManager.ServerCertificateValidationCallback = CertificateValidationResult;
        }

        /// <summary>
        ///  证书验证回调函数  
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="cer"></param>
        /// <param name="chain"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public static bool CertificateValidationResult(object obj, System.Security.Cryptography.X509Certificates.X509Certificate cer, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors error)
        {
            return true;
        }
    }
}
